<template>
  <div>
    <el-card v-loading="loading" shadow="never" body-style="padding-bottom: 0;">
      <el-row :gutter="15">
        <el-col :md="6" style="margin-bottom: 15px;">
          <!-- 操作按钮 -->
          <div class="ele-table-tool ele-table-tool-default">
            <el-button type="primary" icon="el-icon-plus" class="ele-btn-icon" size="small" @click="showEdit=true">添加
            </el-button>
            <el-button
              type="warning"
              icon="el-icon-edit"
              class="ele-btn-icon"
              :disabled="!current"
              size="small"
              @click="edit"
            >修改
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              class="ele-btn-icon"
              :disabled="!current"
              size="small"
              @click="remove"
            >删除
            </el-button>
          </div>
          <!-- 机构列表 -->
          <div class="org-tree-group">
            <el-tree
              ref="orgTree"
              :data="data"
              :props="{label:'name'}"
              :expand-on-click-node="false"
              node-key="id"
              :default-expand-all="true"
              highlight-current
              @node-click="choose"
            />
          </div>
        </el-col>
        <el-col :md="18" style="margin-bottom: 15px;">
          <user-list v-if="current" :organization-id="current.id" :organization-list="organizationList" :department-name="current.name" />
        </el-col>
      </el-row>
    </el-card>
    <!-- 编辑弹窗 -->
    <el-dialog
      :title="editForm.id?'修改机构':'添加机构'"
      :visible.sync="showEdit"
      width="600px"
      :destroy-on-close="true"
      custom-class="ele-dialog-form"
      :lock-scroll="false"
      @closed="editForm={}"
    >
      <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="82px">
        <el-row :gutter="15">
          <el-col :sm="24">
            <el-form-item label="上级部门:">
              <treeselect
                v-model="editForm.parent"
                :options="organizationList"
                placeholder="请选择上级部门"
                :default-expand-level="4"
                :normalizer="(d)=>{return { id: d.id, label: d.name }}"
              />
            </el-form-item>
            <el-form-item label="部门名称:" prop="name">
              <el-input v-model="editForm.name" placeholder="请输入部门名称" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="showEdit=false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect' // 下拉树
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import UserList from '../components/userList'
import { createDepartment, delDepartment, updateDepartment } from '@/api/base'

export default {
  name: 'SysOrganization',
  components: { UserList, Treeselect },
  data() {
    return {
      loading: true, // 加载状态
      data: [], // 列表数据
      where: {}, // 搜索条件
      current: null, // 选中数据
      showEdit: false, // 是否显示表单弹窗
      editForm: {

      }, // 表单数据
      editRules: { // 表单验证规则
        name: [
          { required: true, message: '请输入机构名称', trigger: 'blur' }
        ]
      },
      organizationList: [] // 全部机构
    }
  },
  mounted() {
    this.query()
  },
  methods: {
    /* 查询 */
    query() {
      this.loading = true
      this.$http.get('/base/list/department/', { params: this.where }).then(res => {
        this.loading = false
        if (res.data.code === 0) {
          const data = res.data.data
          data.map(item => {
            if (item.parent_id === 'None') {
              item.parent_id = 0
            }
          })
          this.data = this.$util.toTreeData(res.data.data, 'id', 'parent_id')
          setTimeout(() => {
            this.choose(this.data[0])
          }, 100)
          if (Object.keys(this.where).length === 0) this.organizationList = this.data
        } else {
          this.$message.error(res.data.msg || '获取数据失败')
        }
      }).catch(e => {
        this.loading = false
        this.$message.error(e.message)
      })
    },
    /* 选择数据 */
    choose(row) {
      if (row != null) {
        this.current = row
        this.$refs.orgTree.setCurrentKey(row.id)
      } else {
        this.current = null
      }
    },
    /* 显示编辑 */
    edit() {
      this.editForm = Object.assign({}, this.current, { parent: this.current.parent_id || null })
      this.showEdit = true
    },
    /* 保存编辑 */
    save() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({ lock: true })
          if (this.editForm.id) {
            updateDepartment(this.editForm).then(res => {
              loading.close()
              if (res.data.code === 0) {
                this.showEdit = false
                this.$message({ type: 'success', message: res.data.msg })
                this.query()
              } else {
                this.$message.error(res.data.msg)
              }
            })
          } else {
            createDepartment(this.editForm).then(res => {
              loading.close()
              if (res.data.code === 0) {
                this.showEdit = false
                this.$message({ type: 'success', message: res.data.msg })
                this.query()
              } else {
                this.$message.error(res.data.msg)
              }
            })
          }
        } else {
          return false
        }
      })
    },
    /* 删除 */
    remove() {
      this.$confirm('确定要删除选中的部门吗?', '提示', { type: 'warning' }).then(() => {
        const loading = this.$loading({ lock: true })
        delDepartment(this.current.id).then(res => {
          loading.close()
          if (res.data.code === 0) {
            this.$message({ type: 'success', message: res.data.msg })
            this.query()
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(e => {
          loading.close()
          this.$message.error(e.message)
        })
      }).catch(() => 0)
    }
  }
}
</script>

<style scoped>
.org-tree-group {
  border: 1px solid hsla(0, 0%, 60%, .15);
  height: calc(100vh - 300px);
  box-sizing: border-box;
}

.org-tree-group >>> .el-tree-node__content {
  height: 40px;
}

.org-tree-group >>> .el-tree-node__content > .el-tree-node__expand-icon {
  margin-left: 10px;
}
</style>
